import 'dart:collection';

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:jd_shop/utils/TencentPlayUtils.dart';
import 'package:jd_shop/widget/SwiperWidgetUtils.dart';
import 'package:provider/provider.dart';

import '../../model/LoveGoods.dart';
import '../../net/Config.dart';
import '../../net/MallmsService.dart';
import '../../provider/AppProvider.dart';
import '../../provider/CartProvider.dart';
import '../../routers/AppRoutes.dart';
import '../../services/ScreenAdaper.dart';
import '../../widget/TextWidget.dart';
import '../../utils/TestUtils.dart' as imageUtils;

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<StatefulWidget> createState() {
    return _HomePageState();
  }
}

// searchGoods
class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {
  var cur = 1;
  var tagerSize = 0;
  var page = Config.PAGECOUNT;
  List<Widget> _itemGoodsWidgetList = [];

  //controller
  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    TencentPlayUtils().init();
    _getData();
    _scrollController.addListener(() {
      //上拉加载更多
      if (_scrollController.position.pixels >
          _scrollController.position.maxScrollExtent - 50) {
        print("上拉加载更多");
        cur++;
        this._getData();
      }
    });
  }

  void _getData() async {
    var params = HashMap<String, dynamic>();
    params["currentPage"] = cur;
    params["pageSize"] = page;
    // params["platForm"] = 3;
    params["platFrom"] = 3;
    MallmsService.getLoveGoods(params).then((value) {
      tagerSize = value.mbGoodsInfoList.length;
      if (cur == 1) {
        _itemGoodsWidgetList = [];
        for (var element in value.mbGoodsInfoList) {
          _itemGoodsWidgetList.add(_itemGoodsWidget(element));
        }
      } else {
        for (var element in value.mbGoodsInfoList) {
          _itemGoodsWidgetList.add(_itemGoodsWidget(element));
        }
      }
      setState(() {});
    });
  }

  var imageList = imageUtils.imageList;

  _hotProductListWidget() {
    return Container(
        height: ScreenAdapter.height(70),
        margin: const EdgeInsets.only(left: 10),
        child: ListView.builder(
          scrollDirection: Axis.horizontal,
          itemCount: 50,
          itemBuilder: (context, index) {
            return Container(
              margin: const EdgeInsets.only(right: 10),
              height: double.infinity,
              width: ScreenAdapter.width(70),
              child: InkWell(
                onTap: () {
                  Fluttertoast.showToast(msg: "点击了第$index条");
                },
                child: Column(
                  children: [
                    Container(
                      height: ScreenAdapter.height(50),
                      color: Colors.white,
                      child: ClipRRect(
                        borderRadius: const BorderRadius.only(
                            topLeft: Radius.circular(5),
                            topRight: Radius.circular(5)),
                        child: Image.network(imageUtils.image_url,
                            fit: BoxFit.cover),
                      ),
                    ),
                    Container(
                      width: double.infinity,
                      height: ScreenAdapter.height(20),
                      alignment: Alignment.center,
                      decoration: const BoxDecoration(
                        borderRadius: BorderRadius.only(
                            bottomLeft: Radius.circular(5),
                            bottomRight: Radius.circular(5)),
                        color: Colors.white,
                      ),
                      child: Text("第$index条"),
                    )
                  ],
                ),
              ),
            );
          },
        ));
  }

  Container _GoodsItemsWidget() {
    return Container(
        margin: EdgeInsets.only(
            left: ScreenAdapter.width(10), right: ScreenAdapter.width(10)),
        child: GridView.builder(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2, // 设置每行显示的列数
            mainAxisSpacing: ScreenAdapter.width(10), // 设置主轴（垂直）间距
            crossAxisSpacing: ScreenAdapter.width(10), // 设置交叉轴（水平）间距
            childAspectRatio: 1 / 1.65, // 设置子项的宽高比，例如 1:1.5
          ),
          itemCount: 10,
          // 设置子项数量
          shrinkWrap: true,
          // 使 GridView 只占用其内容所需的空间
          physics: NeverScrollableScrollPhysics(),
          // 禁用 GridView 的滚动效果
          itemBuilder: (BuildContext context, int index) {
            return InkWell(
              onTap: () {
                Fluttertoast.showToast(msg: "点击了第$index条");
              },
              child: Container(
                padding: EdgeInsets.all(ScreenAdapter.width(0)),
                decoration: BoxDecoration(
                    border:
                        Border.all(color: const Color(0xFF9F8CFF), width: 1),
                    borderRadius: BorderRadius.circular(6),
                    color: Colors.white),
                child: Column(
                  children: [
                    AspectRatio(
                      aspectRatio: 1 / 1,
                      child: ClipRRect(
                        borderRadius: const BorderRadius.only(
                            topLeft: Radius.circular(5),
                            topRight: Radius.circular(5)),
                        child: Image.network(imageUtils.image_url,
                            fit: BoxFit.cover),
                      ),
                    ),
                    Container(
                      width: double.infinity,
                      alignment: Alignment.centerLeft,
                      padding: EdgeInsets.all(ScreenAdapter.width(10)),
                      child: Text(
                        "2019夏季新款气质高贵洋气阔太太有女人味中长款宽松大码 $index",
                        maxLines: 2,
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.only(
                          left: ScreenAdapter.width(10),
                          right: ScreenAdapter.width(10)),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          TextWidget(
                            "¥ 99.00",
                            fontSize: 16,
                            color: Colors.red,
                          ),
                          TextWidget(
                            "¥ 99.00",
                            fontSize: 16,
                            color: Colors.grey,
                          ),
                        ],
                      ),
                    )
                  ],
                ),
              ),
            );
          },
        ));
  }

  Widget _itemGoodsWidget(MbGoodsInfoList goodsInfoList) {
    return Container(
        color: Colors.white,
        width: (ScreenAdapter.getScreenWidth() - 30) / 2,
        child: InkWell(
            onTap: () {
              // Fluttertoast.showToast(msg: " ${goodsInfoList.commonName}");
              Navigator.pushNamed(context, AppRoutes.GOODS_DETAIL, arguments: {
                "goodsId": goodsInfoList.goodsId,
                "commonId": goodsInfoList.commonId,
              });
            },
            child: Container(
              padding: EdgeInsets.all(ScreenAdapter.width(0)),
              decoration: BoxDecoration(
                  border: Border.all(
                      color: const Color.fromARGB(100, 255, 255, 255),
                      width: 1),
                  borderRadius: BorderRadius.circular(6),
                  color: Colors.white),
              child: Column(
                children: [
                  AspectRatio(
                    aspectRatio: 1 / 1,
                    child: ClipRRect(
                      borderRadius: const BorderRadius.only(
                          topLeft: Radius.circular(5),
                          topRight: Radius.circular(5)),
                      child: Image.network(goodsInfoList.commonImage,
                          fit: BoxFit.cover),
                    ),
                  ),
                  Container(
                    width: double.infinity,
                    alignment: Alignment.centerLeft,
                    padding: EdgeInsets.all(ScreenAdapter.width(10)),
                    child: Text(
                      "${goodsInfoList.commonName}",
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.only(
                        left: ScreenAdapter.width(10),
                        right: ScreenAdapter.width(10)),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        TextWidget(
                          "¥ ${goodsInfoList.commonPrice}",
                          fontSize: 16,
                          color: Colors.red,
                        ),
                        Text("¥ ${goodsInfoList.commonMarketPrice}",
                            style: const TextStyle(
                                color: Colors.grey,
                                fontSize: 16,
                                decoration: TextDecoration.lineThrough))
                      ],
                    ),
                  ),
                ],
              ),
            )));
  }

  _recProductListWidget() {
    return Container(
      margin: const EdgeInsets.only(left: 10, right: 10),
      child: Wrap(spacing: 10, runSpacing: 10, children: _itemGoodsWidgetList),
    );
  }

  Future<void> _handleRefresh() async {
    // 重置分页参数
    cur = 1;
    _getData();
  }

  @override
  Widget build(BuildContext context) {
    ScreenAdapter.init(context);
    // var mAppProvider = context.watch<AppProvider>();
    // mAppProvider.setContext(context);
    return MediaQuery.removePadding(
        removeTop: true,
        context: context,
        child: RefreshIndicator(
            onRefresh: _handleRefresh,
            child: ListView(
              controller: _scrollController,
              children: [
                defaultSwiperWidget(imageList),
                labelTitleWidget("猜你喜欢"),
                _hotProductListWidget(),
                labelTitleWidget("热门推荐"),
                _recProductListWidget()
              ],
            )));
  }

  @override
  bool get wantKeepAlive => true;
}
